
package com.fire.web.modules.all.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fire.web.modules.all.constant.ErrorCodeConstants;
import com.fire.web.modules.all.entity.*;
import com.fire.web.modules.all.mapper.BuildingMapper;
import com.fire.web.modules.all.mapper.FireProprietorMapper;
import com.fire.web.modules.all.mapper.FireProprietorUserMapper;
import com.fire.web.modules.all.mapper.SiteMapper;
import com.fire.web.modules.all.request.AddSiteReq;
import com.fire.web.modules.all.service.ISiteService;
import com.smartthing.rest.client.SmartThingClient;
import com.smartthing.rest.model.device.Site;
import com.smartthing.rest.model.device.SiteMapData;
import com.smartthing.rest.model.device.request.SiteCreateRequest;
import com.smartthing.spi.SmartThingException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 站点Service
 *
 * @author Matthew
 * @Date 2019-01-17 20:50
 */
@Service
public class SiteServiceImpl extends ServiceImpl<SiteMapper, SiteModel> implements ISiteService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SiteServiceImpl.class);

    @Autowired
    private SiteMapper siteMapper;

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private SmartThingClient smartThingClient;

    @Autowired
    private FireProprietorMapper fireProprietorMapper;
    @Autowired
    private FireProprietorUserMapper fireProprietorUserMapper;

    @Override
    public SiteModel selectOne(SiteModel entity){
        return siteMapper.selectOne(entity);
    }

    @Override
    public List<SiteModel>selectList(SiteModel model){
        return siteMapper.selectListByModel(model);
    }

    @Override
    public Page<SiteModel> selectPage(int currentPage, int pageSize, Wrapper<SiteModel> wrapper){
        return selectPage(new Page<SiteModel>(currentPage,pageSize), wrapper);
    }

    @Override
    public Page<Map<String, Object>> selectMapsPage(int currentPage, int pageSize, Wrapper<SiteModel> wrapper){
        return selectMapsPage(new Page<SiteModel>(currentPage,pageSize), wrapper);
    }

    /**
     * 查询站点详情
     * @param siteId 站点ID
     * @return
     */
    @Override
    public Map querySiteDetail(String siteId){
        return siteMapper.querySiteDetail(siteId);
    }

    /**
     * 查询站点列表（分页）
     * @param page
     * @param column
     * @param columbValue
     * @return
     */
    @Override
    public Page<Map<String,Object>> querySiteList(Page<Map<String,Object>> page, String column, String columbValue){
        return page.setRecords(siteMapper.querySiteList(page, column, columbValue));
    }

    /**
     * 我管理的维保公司（分页）
     * @param page
     * @param supervisorId
     * @return
     */
    @Override
    public Page<Map<String,Object>> queryMyMaitainorsList(Page<Map<String,Object>> page, String supervisorId){
        return page.setRecords(siteMapper.queryMyMaitainorsList(page, supervisorId));
    }

    /**
     * 我管理的业主单位（分页）
     * @param page
     * @param supervisorId
     * @return
     */
    @Override
    public Page<Map<String,Object>> queryMyProprietorsList(Page<Map<String,Object>> page, String supervisorId){
        return page.setRecords(siteMapper.queryMyProprietorsList(page, supervisorId));
    }

    /**
     * 查询用户关联站点列表
     * @param page
     * @param authority
     * @param userId
     * @param wrapper
     * @return
     */
    @Override
    public Page<SiteModel> querySiteAuthorOwnList(Page<SiteModel> page, String authority, String userId, Wrapper<SiteModel> wrapper){
        Page<SiteModel> pageBean = null;
        String supervisor = "supervisor";
        if(supervisor.equals(authority)){
            LOGGER.info("supervisor用户");
            pageBean = page.setRecords(siteMapper.querySiteBySupervisorAdminId(page,userId,wrapper));
        }
        String maintainor = "maintainor";
        if(maintainor.equals(authority)){
            LOGGER.info("maintainor用户");
            pageBean = page.setRecords(siteMapper.querySiteByMaintainorAdminId(page,userId,wrapper));
        }
        String proprietor = "proprietor";
        if(proprietor.equals(authority)){
            LOGGER.info("proprietor用户");
            pageBean = page.setRecords(siteMapper.querySiteByProprietorAdminId(page,userId,wrapper));
        }
        return pageBean;
    }

    @Override
    public AjaxResult addSiteInSmartThing(AddSiteReq req,String adminId){
        AjaxResult result = null;
        try {
            FireProprietorModel fireProprietorModel = new FireProprietorModel();
            fireProprietorModel.setAdminid(adminId);
            fireProprietorModel = fireProprietorMapper.selectOne(fireProprietorModel);
            req.setProprietor(fireProprietorModel.getProprietor());
            req.setProprietorname(fireProprietorModel.getCommanyname());
            String web = fireProprietorModel.getWeb();
            if(com.fire.common.utils.StringUtils.isNotBlank(web)){
                req.setSiteurl(web);
            }else {
                req.setSiteurl("http://www.baidu.com");
            }

            // 校验业主单位是否已存在
            Wrapper proprietorWrapper = new EntityWrapper();
            proprietorWrapper.eq("proprietor",req.getProprietor());
            int proprietorCount = siteMapper.selectCount(proprietorWrapper);
            if(proprietorCount > 0){
                return new AjaxResult(ErrorCodeConstants.PRODUCT_PARAMERROR, "站点创建失败,业主单位已存在", "站点创建失败,业主单位已存在");
            }
            Wrapper siteWrapper = new EntityWrapper();
            siteWrapper.eq("buildingid",req.getBuildingid());
            List<SiteModel> siteList = siteMapper.selectList(siteWrapper);
            if(siteList.size() != 0){
                LOGGER.error("建筑ID对应站点数为"+siteList.size());
                return new AjaxResult(ErrorCodeConstants.PRODUCT_PARAMERROR, "站点创建失败，建筑已关联使用", "站点创建失败，建筑已关联使用");
            }
            // 准备调用smartThing数据
            // 生成token
            String token = UUID.randomUUID().toString();

            // 调用smartThing
            SiteCreateRequest request = new SiteCreateRequest();
            // 站点详情
            request.setToken(token);
            request.setName(req.getSitename());
            request.setImageUrl(req.getSiteimageurl());
            request.setDescription(req.getDescriptor());

            // 地图信息
            String mapDataType = "openstreetmap";
            SiteMapData siteMapData = new SiteMapData();
            siteMapData.setType(mapDataType);
            // 建筑物表取经纬度信息
//            Wrapper buildingWrapper = new EntityWrapper();
//            buildingWrapper.eq("buldingid",req.getBuildingid());
            BuildingModel building = buildingMapper.selectById(req.getBuildingid());
            if(building == null){
                return new AjaxResult(ErrorCodeConstants.PRODUCT_PARAMERROR, "站点创建失败，无建筑信息", "站点创建失败，无建筑信息");
            }
            if(StringUtils.isNotEmpty(building.getLatitude()) && StringUtils.isNotEmpty(building.getLongitude())){
                siteMapData.addOrReplaceMetadata("zoomLevel","15");
                siteMapData.addOrReplaceMetadata("centerLatitude",building.getLatitude());
                siteMapData.addOrReplaceMetadata("centerLongitude",building.getLongitude());
            }
            request.setMap(siteMapData);

            // 元数据
            Map<String,String> metadata = new HashMap<>();
            metadata.put("siteurl",req.getSiteurl());
            metadata.put("buildingid",req.getBuildingid());
            metadata.put("buildingname",req.getBuildingname());
            metadata.put("maintainor",req.getMaintainor());
            metadata.put("maintainname",req.getMaintainname());
            metadata.put("supervisorid",req.getSupervisorid());
            metadata.put("supervisorname",req.getSupervisorname());
            metadata.put("proprietor",req.getProprietor());
            metadata.put("proprietorname",req.getProprietorname());
            request.setMetadata(metadata);

            Site site = smartThingClient.createSite(request);


            // 成功调用smartThing后数据写入数据库
            SiteModel siteModel = new SiteModel();
            siteModel.setSiteid(token);
            siteModel.setSitetoken(token);
            siteModel.setSitename(req.getSitename());
            siteModel.setSiteurl(req.getSiteurl());
            siteModel.setSiteimageurl(req.getSiteimageurl());
            siteModel.setDescriptor(req.getDescriptor());
            siteModel.setBuildingid(req.getBuildingid());
            siteModel.setBuildingname(req.getBuildingname());
            siteModel.setMaintainname(req.getMaintainname());
            siteModel.setMaintainor(req.getMaintainor());
            siteModel.setProprietor(req.getProprietor());
            siteModel.setProprietorname(req.getProprietorname());
            siteModel.setSupervisorid(req.getSupervisorid());
            siteModel.setSupervisorname(req.getSupervisorname());
            siteModel.setCreatetime(new Date());
            siteModel.setUpdatetime(new Date());
            siteMapper.insert(siteModel);
            // 回写业主单位表监管单位数据
            FireProprietorModel fireProprietor = fireProprietorMapper.selectById(req.getProprietor());
            if("".equals(fireProprietor.getSupervisorid()) || "".equals(fireProprietor.getSupervisorname())){
                fireProprietor.setSupervisorid(req.getSupervisorid());
                fireProprietor.setSupervisorname(req.getSupervisorname());
                fireProprietor.setUpdatetime(new Date());
                fireProprietorMapper.updateById(fireProprietor);
            }
            result = new AjaxResult(ErrorCodeConstants.SUCCESS, "站点创建成功", "站点创建成功");
        } catch (SmartThingException e) {
            LOGGER.error("SiteServiceImpl.addSite().error  错误为：", e);
            result = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
        }
        return result;
    }

    @Override
    public AjaxResult deleteSiteInSmartThing(String siteToken) {
        AjaxResult result = null;
        try {
            // smartThing删除
            smartThingClient.deleteSite(siteToken,false);

            // 数据库删除
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("siteToken",siteToken);
            siteMapper.delete(wrapper);
            result = new AjaxResult(ErrorCodeConstants.SUCCESS, "站点删除成功", "站点删除成功");
        } catch (SmartThingException e) {
            LOGGER.error("SiteServiceImpl.deleteSiteInSmartThing().error  错误为：", e);
            result = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
        }
        return result;
    }

    @Override
    public AjaxResult updateSiteInSmartThing(AddSiteReq req){
        AjaxResult result = null;
        try {
            // 准备调用smartThing数据
            // 调用smartThing
            SiteCreateRequest request = new SiteCreateRequest();
            // 站点详情
            request.setToken(req.getSitetoken());
            request.setName(req.getSitename());
            request.setImageUrl(req.getSiteimageurl());
            request.setDescription(req.getDescriptor());

            // 地图信息
            String mapDataType = "openstreetmap";
            SiteMapData siteMapData = new SiteMapData();
            siteMapData.setType(mapDataType);
//            Map<String,String> mapMetadata = new HashMap<>();
//            mapMetadata.put("zoomLevel","0");
//            mapMetadata.put("centerLatitude","0");
//            mapMetadata.put("centerLongitude","0");
            request.setMap(siteMapData);

            // 元数据
            Map<String,String> metadata = new HashMap<>();
            metadata.put("siteurl",req.getSiteurl());
            metadata.put("buildingid",req.getBuildingid());
            metadata.put("buildingname",req.getBuildingname());
            metadata.put("maintainor",req.getMaintainor());
            metadata.put("maintainname",req.getMaintainname());
            metadata.put("supervisorid",req.getSupervisorid());
            metadata.put("supervisorname",req.getSupervisorname());
            metadata.put("proprietor",req.getProprietor());
            metadata.put("proprietorname",req.getProprietorname());
            request.setMetadata(metadata);

            Site site = smartThingClient.updateSite(req.getSitetoken(),request);

            // 成功调用smartThing后数据写入数据库
            SiteModel siteModel = new SiteModel();
            siteModel.setSiteid(req.getSiteid());
            siteModel.setSitetoken(req.getSitetoken());
            siteModel.setSitename(req.getSitename());
            siteModel.setSiteurl(req.getSiteurl());
            siteModel.setSiteimageurl(req.getSiteimageurl());
            siteModel.setDescriptor(req.getDescriptor());
            siteModel.setBuildingid(req.getBuildingid());
            siteModel.setBuildingname(req.getBuildingname());
            siteModel.setMaintainname(req.getMaintainname());
            siteModel.setMaintainor(req.getMaintainor());
            siteModel.setProprietor(req.getProprietor());
            siteModel.setProprietorname(req.getProprietorname());
            siteModel.setSupervisorid(req.getSupervisorid());
            siteModel.setSupervisorname(req.getSupervisorname());
            siteModel.setUpdatetime(new Date());
            siteMapper.updateAllColumnById(siteModel);
            // 回写业主单位表监管单位数据
            FireProprietorModel fireProprietor = fireProprietorMapper.selectById(req.getProprietor());
            if("".equals(fireProprietor.getSupervisorid()) || "".equals(fireProprietor.getSupervisorname())){
                fireProprietor.setSupervisorid(req.getSupervisorid());
                fireProprietor.setSupervisorname(req.getSupervisorname());
                fireProprietor.setUpdatetime(new Date());
                fireProprietorMapper.updateById(fireProprietor);
            }
            result = new AjaxResult(ErrorCodeConstants.SUCCESS, "站点更新成功", "站点更新成功");
        } catch (SmartThingException e) {
            LOGGER.error("SiteServiceImpl.updateSite().error  错误为：", e);
            result = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
        }
        return result;
    }

}
